package com.haima.ziliao.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.haima.common.annotation.Log;
import com.haima.common.annotation.RepeatSubmit;
import com.haima.common.core.controller.BaseController;
import com.haima.common.core.domain.AjaxResult;
import com.haima.common.core.page.TableDataInfo;
import com.haima.common.enums.BusinessType;
import com.haima.common.utils.DateUtils;
import com.haima.common.utils.SecurityUtils;
import com.haima.common.utils.poi.ExcelUtil;
import com.haima.utils.RandomStringGenerator;
import com.haima.ziliao.domain.PCdkeys;
import com.haima.ziliao.domain.PUservip;
import com.haima.ziliao.service.IPCdkeysService;
import com.haima.ziliao.service.IPUservipService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.List;

/**
 * 兑换码Controller
 * 
 * @author hima
 * @date 2025-05-19
 */
@RestController
@RequestMapping("/ziliao/cdkeys")
public class PCdkeysController extends BaseController
{
    @Autowired
    private IPCdkeysService pCdkeysService;
    @Autowired
    private IPUservipService uservipService;

    /**
     * 查询兑换码列表
     */
    @PreAuthorize("@ss.hasPermi('system:cdkeys:list')")
    @GetMapping("/list")
    public TableDataInfo list(PCdkeys pCdkeys)
    {
        startPage();
        List<PCdkeys> list = pCdkeysService.selectPCdkeysList(pCdkeys);
        return getDataTable(list);
    }

    @GetMapping("/listCdkeysAll")
    public AjaxResult listCdkeysAll (PCdkeys pCdkeys) {
        List<PCdkeys> list = pCdkeysService.selectPCdkeysList(pCdkeys);
        return AjaxResult.success(list);
    }

    @RepeatSubmit
    @GetMapping("/duihuan")
    public AjaxResult duihuan (PCdkeys pCdkeys) {
        String key = pCdkeys.getKeystr();

        PCdkeys cdkeys = pCdkeysService.getOne(new QueryWrapper<PCdkeys>()
                .eq("keystr",key));

        if(cdkeys==null){
            return AjaxResult.error("兑换码错误");
        }
        if(cdkeys.getUsed()!=0){
            return AjaxResult.error("兑换码已被使用");
        }
        cdkeys.setUseuid(SecurityUtils.getUserId());
        cdkeys.setUsed(1);
        cdkeys.setUpdtime(DateUtils.getNowDate());

        pCdkeysService.updatePCdkeys(cdkeys);

        //增加会员
        //处理VIP信息
        Long uid = SecurityUtils.getUserId();
        PUservip vip = uservipService.getOne(new QueryWrapper<PUservip>().eq("uid",uid));

        if(vip==null){//新增VIP
            PUservip nvip = new PUservip();
            nvip.setUid(uid);
            nvip.setStatus("1");
            nvip.setStartTime(DateUtils.getNowDate());
            nvip.setEndTime(DateUtils.addDays(nvip.getStartTime(),cdkeys.getDays()));
            nvip.setType(cdkeys.getVid().toString());
            uservipService.insertPUservip(nvip);
        }else{
            vip.setStatus("1");
            Date endTime = vip.getEndTime();
            if(endTime.before(DateUtils.getNowDate())){//如果当前时间大于结束时间，则从今日开始续费
                vip.setEndTime(DateUtils.addDays(DateUtils.getNowDate(),cdkeys.getDays()));
            }else if(endTime.after(DateUtils.getNowDate())){//如果当前时间小于结束时间，则从结束时间开始续费
                vip.setEndTime(DateUtils.addDays(endTime,cdkeys.getDays()));
            }else {//如果当前时间等于结束时间，则无所谓
                vip.setEndTime(DateUtils.addDays(DateUtils.getNowDate(),cdkeys.getDays()));
            }
            uservipService.updatePUservip(vip);
        }
        return AjaxResult.success("兑换成功");
    }

    /**
     * 导出兑换码列表
     */
    @PreAuthorize("@ss.hasPermi('system:cdkeys:export')")
    @Log(title = "兑换码", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, PCdkeys pCdkeys)
    {
        List<PCdkeys> list = pCdkeysService.selectPCdkeysList(pCdkeys);
        ExcelUtil<PCdkeys> util = new ExcelUtil<PCdkeys>(PCdkeys.class);
        util.exportExcel(response, list, "兑换码数据");
    }

    /**
     * 获取兑换码详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:cdkeys:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(pCdkeysService.selectPCdkeysById(id));
    }

    /**
     * 新增兑换码
     */
    @Log(title = "兑换码", businessType = BusinessType.INSERT)
    @PostMapping("/genCdKey")
    public AjaxResult genCdKey(@RequestBody PCdkeys pCdkeys)
    {
        for(int i=0;i<pCdkeys.getNum();i++){
            String cdk = RandomStringGenerator.generateRandomString(12);
            pCdkeys.setKeystr(cdk);
            pCdkeys.setAddtime(DateUtils.getNowDate());
            pCdkeys.setUsed(0);
            pCdkeysService.insertPCdkeys(pCdkeys);
        }
        return AjaxResult.success(pCdkeys);
    }

    @Log(title = "生成兑换码", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody PCdkeys pCdkeys)
    {
        return toAjax(pCdkeysService.insertPCdkeys(pCdkeys));
    }

    /**
     * 修改兑换码
     */
    @PreAuthorize("@ss.hasPermi('system:cdkeys:edit')")
    @Log(title = "兑换码", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody PCdkeys pCdkeys)
    {
        return toAjax(pCdkeysService.updatePCdkeys(pCdkeys));
    }

    /**
     * 删除兑换码
     */
    @PreAuthorize("@ss.hasPermi('system:cdkeys:remove')")
    @Log(title = "兑换码", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(pCdkeysService.deletePCdkeysByIds(ids));
    }
}
